package com.example.forum.interceptor;

import com.example.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author YJ
 * @Date 2023/8/17 14:50
 * Description:登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${my-forum.login.url}")
    private String defaultURL;

    /**
     * 前置处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前置处理
        //1.获取session
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            return true;
        }
        //检验url是否正确
        if (!defaultURL.startsWith("/")) {
            defaultURL = "/" + defaultURL ;
        }
        //2.校验不通过，跳转到登录界面
        response.sendRedirect(defaultURL);
        return false;
    }
}
